/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parser.nodes;

import codegen.CodeGen;
import scanner.Token;
import static scanner.TokenType.*;

// Factor = ident Selector | integer | string | Read | '(' Expression ')'
public class FactorNode extends Node {
    private Token integer, string;   //Terminals
    private ExpressionNode expression;      //Nonterminals
    private ReadNode read; 
    private DereferenceNode ident;

    public FactorNode(Token generic) {
        if (generic.type() == INTEGER)
            integer = generic;
        else if (generic.type() == STRING)
            string = generic;
    }

    public FactorNode(Token ident, SelectorNode Selector) {
        this.ident = new ContNode(ident, Selector);
    }

    public FactorNode(ReadNode read) {
        this.read = read;
    }
	
	public void removeCont() {
		if (ident instanceof ContNode) {
			ident = ((ContNode)ident).getSubstitution();
		}
	}

    public FactorNode(ExpressionNode expression) {
        this.expression = expression;
    }

    @Override
    public void print() {
        p("Factor: ");
        indent();
        if (ident != null)  {
            ident.print();
        } else if (integer != null)
            p(integer);
        else if (string != null)
            p(string);
        else if (read != null)
            read.print();
        else if (expression != null) {
            p("(");
            expression.print();
            p(")");
        }
        unindent();
    }

    @Override
    public void abstractPrint() {
        if (ident != null)  {
            ident.abstractPrint();
        } else if (integer != null)
            p(integer);
        else if (string != null)
            p(string);
        else if (read != null)
            read.abstractPrint();
        else if (expression != null) {
            p("()");
            indent();
            expression.abstractPrint();
            unindent();
        }
    }

    @Override
    public void compile(CodeGen c) throws CompileError {
        if (ident != null)
            ident.compile(c);
        else if (integer != null)
            c.outstr("PUSHI, " + Integer.parseInt(integer.toString()));
        else if (string != null)
            c.outstr("PUSHS, " + string.toString());
        else if (read != null)
            read.compile(c);
        else if (expression != null) {
            expression.compile(c);
        }
    }
}
